<template>
  <div class="app-container">
    <div class="searchform">
    <ToolBar :filters="filters" :getList="getList" :handleAdd="handleCreate"/>
    </div>
    <div class="customerselect">
    <span>当前客户</span>
    <customer-select :selected="customerid" @changeVal="toggleChange"></customer-select>
    </div>
    <el-table v-loading="listLoading" :data="customerList" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="ID" prop="id" width="95" type="index" >
      </el-table-column>
      <el-table-column label="公司名称" min-width="200" >
        <template slot-scope="scope">
          {{ scope.row.customerName }}
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" min-width="100" >
        <template slot-scope="scope">
          <span>{{ scope.row.contactPerson }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center">
        <template slot-scope="scope">
          {{ scope.row.contactNumber }}
        </template>
      </el-table-column>
      <el-table-column label="客户编码" align="center">
        <template slot-scope="scope">
          {{ scope.row.customerCode }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="250" align="center">
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="handleMember(scope.$index, scope.row)" >成员</el-button>
          <el-button size="small" type="warning" @click="handleUpdate(scope.$index, scope.row)" >
            <i class="el-icon-edit"></i>
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDel(scope.$index, scope.row)" ></el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!--翻页-->
    <el-col :span="24" class="toolbar">
    <Pagination v-show="total>0" :total="total" :pageSize='pagesize' :handleCurrentChange="handleCurrentChange" />
    </el-col>

    <!--弹窗界面-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
       <el-form label-width="100px" :model="Form" :rules="FormRules" ref="dataForm">
        <el-form-item label="公司名称" prop="customerName" width="100%">
          <el-input v-model="Form.customerName"></el-input>
        </el-form-item>
        <el-form-item label="公司地址" prop="customerAddress" width="100%">
          <el-input v-model="Form.customerAddress"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson" width="100%">
          <el-input v-model="Form.contactPerson"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactNumber" width="100%">
          <el-input v-model="Form.contactNumber"></el-input>
        </el-form-item>
        
        <el-form-item label="客户编码" prop="customerCode" width="100%" >
          <el-tooltip class="item" effect="dark" content="客户名称首字母大写，7位，不足7位补0；如（SYCZYY0）" placement="top-start">
           <el-input v-model="Form.customerCode"></el-input>
          </el-tooltip>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary"  @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import { getCustomerList, createCustomer, updateCustomer, deleteCustomer } from "@/api/customers";
import {isvalidPhone} from '@/utils/validate'
import ToolBar from "@/views/layout/components/ToolBar";
import CustomerSelect from "@/views/layout/components/CustomerSelect";
import Pagination from "@/views/layout/components/Pagination";
import { mapGetters, mapActions } from "vuex";

const validPhone=(rule, value,callback)=>{
      if (!value){
          callback(new Error('请输入电话号码'))
      }else  if (!isvalidPhone(value)){
        callback(new Error('请输入正确的11位手机号码'))
      }else {
          callback()
      }
  }
export default {
  components: { ToolBar, Pagination, CustomerSelect},

  data() {
    return {
      filters: {
        name: "",
        placeholder: "客户名称或Code"
      },
      page: 1,
      total: 0,
      pagesize: 10,
      customerList: [],
      listLoading: false,

      dialogStatus: "",
      textMap: {
        update: "编辑客户",
        create: "新增客户"
      },
      dialogFormVisible: false,
      Form:{
        contactNumber: '',
        contactPerson: '',
        customerAddress: '',
        customerCode: '',
        customerName: '',
      },
      FormRules: {
        customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
        customerAddress: [{ required: true, message: '请输入客户地址', trigger: 'blur' }],
        customerCode: [{ required: true, message: '请输入客户编码', trigger: 'blur' }],
        contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        contactNumber: [{ required: true, trigger: 'blur', validator: validPhone}],
      },
      
    };
  },
  created() { 
    this.getList();
  },
  computed: {
    ...mapGetters(["customername","customerid"])
  },
  methods: {
    ...mapActions(["SetCustomerInfo"]),
    toggleChange(customerid, customername){
      this.SetCustomerInfo({
        customerid,
        customername
      });
    },

    //跳转成员列表
    handleMember(index, row){
      this.$router.push({
        path:'/customers/customerMember/'+ row.id
      })
    },
    // 获取列表
    getList() {
      this.listLoading = true;
      getCustomerList({
        name: this.filters.name,
        page: this.page,
        size: this.pagesize
      })
        .then(response => {
          this.customerList = response.data.records;
          this.total = response.data.total;
          this.listLoading = false;
        })
        .catch(e => { });
    },
    // 翻页
    handleCurrentChange(val) {
      this.page = val;
      this.getList();
    },

    //重置form
    resetForm() {
      this.Form = {
        contactNumber: '',
        contactPerson: '',
        customerAddress: '',
        customerCode: '',
        customerName: '',
      }
    },
    // 显示增加界面
    handleCreate() {
      this.resetForm(),
      this.dialogStatus = 'create'
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })    
    },

    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createCustomer(this.Form).then(() => {
            this.customerList.push(this.Form)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
     },

    //显示编辑界面
    handleUpdate(index,row) {
      this.Form = Object.assign(this.Form, row);
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
     //编辑数据
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.Form)
          updateCustomer(tempData).then(() => {
            for (const customer of this.customerList) {
              if (customer.id === this.Form.id) {
                const index = this.customerList.indexOf(customer)
                this.customerList.splice(index, 1, this.Form)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleDel(index,row) {
      this.$confirm("确认删除该客户吗?", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning"
      }).then(()=>{
        this.listLoading = true;
        deleteCustomer({id:row.id}).then(() => {
          this.listLoading = false;
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
           })
          const index = this.customerList.indexOf(row)
          this.customerList.splice(index, 1)
         })

      }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      
    },
    
  }
};
</script>
<style scoped>
.searchform{
  float: left;
}
.customerselect{
  color:#606266;
  font-size: 14px;
  float: left;
}
</style>


